<?php

namespace app\Http\Controllers\API;

use Auth;
use App\User;
use App\Game;
use App\Comment;
use App\GameRecord;
use App\GameError;
use App\GameStatistics;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;

class GameController extends Controller
{
    public function query()
    {
        $category_id = request('category_id');
        $page_size = request('page_size');
        $page_index = request('page_index');
        $games = Game::where('category_id', $category_id)->where('status', 1)->skip($page_index * $page_size)->take($page_size)->orderBy('star', 'desc')->get();
        foreach($games as &$game){
            $game->desc = str_replace("\n", "<br/>", $game->desc);
        }
        return response()->json($games);
    }

    public function show($id)
    {
        $game = Game::find($id);
        return response()->json($game);
    }

    public function records()
    {
        $game_id = request('game_id');
        $user = Auth::user();
        $user_id = $user->id;
        $records = GameRecord::where('game_id', $game_id)->where('user_id', $user_id)->get();
        return response()->json($records);
    }

    public function save()
    {
        $game_id = request('game_id');
        $name = request('name');
        $data = request('data');
        $user = Auth::user();
        $user_id = $user->id;
        $record = GameRecord::where('game_id', $game_id)->where('user_id', $user_id)->where('name', $name)->first();
        if(empty($record)){
            $record = new GameRecord();
            $record->user_id = $user_id;
            $record->game_id = $game_id;
        }
        $record->status = 0;
        $record->name = $name;
        $record->data = $data;
        $record->save();
        return response()->json(['code' => 0]);
    }

    public function rank()
    {
        $game_id = request('game_id');
        $result = GameStatistics::where('game_id', $game_id)->orderBy('score', 'desc')->select('user_name', 'score', 'user_id', 'id')->get();
        return response()->json($result);
    }

    public function statistics()
    {
        $id = request('id');
        $result = GameStatistics::where('id', $id)->first();
        return response()->json($result);
    }

    public function error(Request $request)
    {

        GameError::create(
            $request->all()
        );
        return response()->json(true);
    }
}
